define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var Detail = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-user").parents("li").addClass("active");
            this.initCityList();
            this.bindEvent();
        },

        bindEvent: function () {
            var self = this;

            $("#updateUser").click(function () {
                var mobile = $("#mobile").val();
                var managerUserId = $("#managerUserId").val();
                var department = $("#department").val();
                var category = $("#category").val();
                var workerId = $("#workerId").val();
                var realName = $("#realName").val();
                var userNick = $("#userNick").val();
                var email = $("#email").val();
                var city = $("#city").val();
                var isDeleted = $("#isDeleted").val();
                var level = $("#audit").val();

                var data = {};
                if (mobile) {
                    data.mobile = mobile;
                }
                if (!$("#leader").val()) {
                    managerUserId = "";
                }
                data.managerUserId = managerUserId;
                data.department = department;
                data.category = category;
                data.workerId = workerId;

                if (realName) {
                    data.realName = realName;
                }
                if (userNick) {
                    data.userNick = userNick;
                }
                if (email) {
                    data.email = email;
                }
                if (city) {
                    data.city = city;
                }else{
                    CRM.showDialog("请选择城市!");
                    return;
                }
                if (isDeleted) {
                    data.isDeleted = isDeleted;
                }
                if (level) {
                    data.level = level;
                }
                if (level != 0 && level != 200) {
                    if (!CRM.checkEmail(email)) {
                        CRM.showDialog("邮件格式不正确!");
                        return;
                    }
                }
                $.ajax({
                    url: CRM.getOuterUrl('/member/updateUserInfoForCRM.do'),
                    contentType: "application/json",
                    type: 'post',
                    dataType: 'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    data: JSON.stringify(data),
                    error: function (error) {
                        console.log(error);
                        alert("修改用户信息出现异常!");
                    },
                    success: function (data) {
                        if (data.status == true && data.responseCode == 0) {
                            alert("修改用户信息成功!");
                        } else {
                            alert(data.message);
                        }
                    }
                });
            });

            $('#leader').typeahead({
                onSelect: function (item) {
                    $("#managerUserId").val(item.value);
                },
                ajax: {
                    url: CRM.getOuterUrl("/dataapi/user/search.do?minlevel=300&start=0&count=100"),
                    displayField: "dis",
                    valueField: "valId",
                    triggerLength: 1,
                    items: 100,
                    method: "get",
                    loadingClass: "loading-circle",
                    preDispatch: function (query) {
                        return {
                            mobile: query,
                            name: query
                        }
                    },
                    preProcess: function (data) {
                        if (data.success === false) {
                            return false;
                        }
                        var docs = data.docs;
                        if (!docs || docs.length == 0) {
                            return false;
                        }
                        for (var j in docs) {
                            var doc = docs[j];
                            doc.dis = doc.mobile + ' ' + doc.realName;
                            doc.valId = doc.userId;
                        }
                        return docs;
                    }
                }
            });

            $("#del_manager").click(function () {
                self.delManager();
            })
        },

        initCityList: function () {
            var self = this;

            CRM.request({
                url: CRM.getOuterUrl('/shop/city/queryOpenCity'),
                type: 'post',
                dataType: 'json',
                data: JSON.stringify({
                    "operator": $.getUrlVar('userId')
                }),
                error: function (error) {
                    console.log(error);
                    alert("获取开通城市信息出现错误!");
                },
                success: function (data) {
                    if (data.status) {
                        for (var i in data.entry) {
                            var cityName = data.entry[i].city;
                            var option = '<option value="' + cityName + '">' + cityName + '</option>';
                            $("#city").append(option);
                        }
                        self.getLoginUserInfo();
                    } else {
                        alert(data.message);
                    }
                }
            });
        },

        getLoginUserInfo: function () {
            var self = this;
            CRM.request({
                url: CRM.getOuterUrl('/member/getUserVO.do'),
                type: 'get',
                xhrFields: {
                    withCredentials: true
                },
                error: function (error) {
                },
                success: function (data) {
                    if (data.status && data.responseCode == 0) {
                        var level = data.entry.level;
                        self.getUserInfo(level);
                    } else {
                        alert(data.message);
                    }
                }
            });
        },

        getUserInfoById: function (userId) {
            CRM.request({
                url: CRM.getOuterUrl('/member/getUserbyUserId.do?userId=' + userId),
                type: 'get',
                error: function (error) {
                    console.log(error);
                    alert("根据用户ID查询用户出现错误!");
                },
                success: function (data) {
                    if (data.status && data.responseCode == 0) {
                        var dis = data.entry.mobile + " " + data.entry.realName;
                        $("#leader").val(dis);
                        $("#managerUserId").val(userId);
                    } else {
                        alert(data.message);
                    }
                }
            });
        },

        getUserInfo: function (loginLevel) {
            var self = this;
            var mobile = $.getUrlVar('mobile');
            CRM.request({
                url: CRM.getOuterUrl('/member/getUserbyMobile.do?mobile=' + mobile),
                type: 'get',
                success: function (data) {
                    if (data.status) {
                        $("#department").val(data.entry.department);
                        $("#category").val(data.entry.category);
                        $("#workerId").val(data.entry.workerId);
                        $("#realName").val(data.entry.realName);
                        $("#userNick").val(data.entry.userNick);
                        $("#mobile").val(data.entry.mobile);
                        $("#email").val(data.entry.email);
                        $("#city").val(data.entry.city);

                        $("#gmtCreate").val(CRM.formatDate(new Date(data.entry.gmtCreate)));
                        if (data.entry.isDeleted) {
                            $("#isDeleted").val(data.entry.isDeleted);
                        } else {
                            $("#isDeleted").val(0);
                        }

                        if (loginLevel > 300) {
                            $("#leader").prop('disabled', false);
                        }
                        $("#userId").val(data.entry.userId);
                        $("#token").val(data.entry.token);
                        $("#apppleToken").val(data.entry.appleToken);
                        $("#remoteUserAgent").val(data.entry.remoteUserAgent);
                        if (loginLevel >= 800) {
                            $("#userId_div").show();
                            $("#token_div").show();
                            $("#apppleToken_div").show();
                            $("#remoteUserAgent_div").show();
                        }else{
                            $("#userId_div").hide();
                            $("#token_div").hide();
                            $("#apppleToken_div").hide();
                            $("#remoteUserAgent_div").hide();
                        }


                        var level = data.entry.level;
                        if (level <= 100) {
                            $("#audit").val(0);
                        } else if (level > 100 && level <= 200) {
                            $("#audit").val(200);
                        } else if (level > 400 && level <= 500) {
                            $("#audit").val(500);
                        } else if (level > 500 && level <= 600) {
                            $("#audit").val(600);
                        } else if (level > 600 && level <= 700) {
                            $("#audit").val(700);
                        } else if (level > 700 && level <= 800) {
                            $("#audit").val(800);
                        } else if (level > 800 && level <= 1000) {
                            $("#audit").val(1000);
                        } else if (level > 1000 && level <= 2000) {
                            $("#audit").val(2000);
                        }

                        var managerUserId = data.entry.managerUserId;
                        if (managerUserId) {
                            self.getUserInfoById(managerUserId);
                        }
                    }
                }
            });
        },
        /**
         * 删除主管
         */
        delManager:function(){
            var self = this;
            if (confirm('确认解除主管关系？')) {
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl("/member/updateUserManager.do"),
                    "dataType": "json",
                    contentType: "application/json",
                    "data": JSON.stringify({
                        mobile:$("#mobile").val()
                    }),
                    "success": function (req) {
                        if (req.status) {
                            CRM.showDialog(req.message);
                            $("#managerUserId").val("");
                            $("#leader").val("");
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }
        }
    };

    Detail.init();
});

